package edu.biwu.advice;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
@Aspect
public class ServiceAdvice02 {
    //在通知中获取目标方法的形参,返回值,抛出异常

    @Pointcut("execution(* edu.biwu.service..*.*(..))")
    public void pointcut(){

    }
//    @Before("execution(* edu.biwu.service..*.*(..))")
//    @Before("pointcut()")
    public void beforeAdvice(JoinPoint joinPoint){
        System.out.println(Arrays.toString(joinPoint.getArgs()) + "  " + joinPoint.getSignature());
        System.out.println("前置通知");
    }
//    @AfterReturning(pointcut = "execution(* edu.biwu.service..*.*(..))",returning = "reVal")
//    @AfterReturning(pointcut = "pointcut()",returning = "reVal")
    public void afterReturningAdvice(JoinPoint joinPoint,Object reVal){
        System.out.println(Arrays.toString(joinPoint.getArgs()) + "  " + joinPoint.getSignature());
        System.out.println("获取返回值:"+reVal);
        System.out.println("后置通知");
    }

//    @After("pointcut()")
    public void finallyAdvice(){
        System.out.println("最终通知");
    }

//    @AfterThrowing(pointcut = "pointcut()",throwing = "throwable")
    public void afterThrowingAdvice(Throwable throwable){
        System.out.println("异常通知");
        System.out.println("获取异常信息:"+throwable.getMessage());
    }

    @Around("pointcut()")
    public void aroundAdvice(ProceedingJoinPoint pjp){
//        System.out.println("环绕通知");
        System.out.println(Arrays.toString(pjp.getArgs()) + "  " + pjp.getSignature());

        try {
            System.out.println("前置通知");
            Object reVal = pjp.proceed();//相当于执行目标方法 (目标方法执行完之后,返回值会赋给reVal)
            System.out.println("获取返回值:"+reVal);
            System.out.println("后置通知");
        } catch (Throwable e) {
            System.out.println("异常通知");
            System.out.println("获取异常信息:"+e.getMessage());
            e.printStackTrace();
        } finally {
            System.out.println("最终通知");
        }
    }
}

